package com.g2room.driving.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import com.g2room.driving.model.to.FtpTo;

public class FtpUtil {
    
    private static Logger logger=Logger.getLogger(FtpUtil.class);
    
    private FTPClient ftp;
    
    /**
     * 获取ftp连接
     * @param f
     * @return
     * @throws Exception
     */
	public boolean connectFtp(FtpTo f) throws Exception {
		ftp = new FTPClient();
		boolean flag = false;
		try {
			int reply;
			if (f.getPort() == null) {
				ftp.connect(f.getIpAddr(), 21);
			} else {
				ftp.connect(f.getIpAddr(), f.getPort());
			}
			ftp.login(f.getUserName(), f.getPwd());
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return flag;
			}
			ftp.setDataTimeout(1800000);       //设置传输超时时间为60秒 
			ftp.setConnectTimeout(1800000);       //连接超时为60秒
			ftp.changeWorkingDirectory(f.getPath());
			flag = true;
		} catch(IOException e) {  
			flag = true;
		      logger.error("ftp disconn err, {}", e);
		} finally {  
		  if(ftp.isConnected()) {  
		    try {
		    	ftp.disconnect();  
		    } catch(IOException ioe) {
		      logger.error("ftp disconn err, {}", ioe);
		    }  
		  }  
		}
		return flag;
	}
    
    /**
     * 关闭ftp连接
     */
    public void closeFtp(){
        if (ftp!=null && ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * ftp上传文件
     * @param f	待上传的文件
     * @param folder	远程上传目录
     * @param mkdir	是否允许创建目录
     * @throws Exception
     */
	public void upload(File f, String folder, boolean mkdir) throws Exception {
		// 切换到指定目录
		if (!StringUtils.isBlank(folder)) {
			ftp.changeWorkingDirectory(folder);
		}

		if (f.isDirectory()) {
			if(mkdir) ftp.makeDirectory(f.getName());
			ftp.changeWorkingDirectory(f.getName());
			String[] files = f.list();
			for (String fstr : files) {
				File file1 = new File(f.getPath() + "/" + fstr);
				if (file1.isDirectory()) {
					upload(file1, folder, true);
					ftp.changeToParentDirectory();
				} else {
					File file2 = new File(f.getPath() + "/" + fstr);
					FileInputStream input = new FileInputStream(file2);
					ftp.storeFile(file2.getName(), input);
					input.close();
				}
			}
		} else {
			FileInputStream input = new FileInputStream(f);
			ftp.storeFile(f.getName(), input);
			input.close();
		}
	}
    
    /**
     * 下载链接配置
     * @param f
     * @param localBaseDir 本地目录
     * @param remoteBaseDir 远程目录
     * @throws Exception
     */
    public void startDown(FtpTo f,String localBaseDir,String remoteBaseDir ) throws Exception{
        if (connectFtp(f)) {
            try { 
                FTPFile[] files = null; 
                boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); 
                if (changedir) { 
                    ftp.setControlEncoding("GBK"); 
                    files = ftp.listFiles(); 
                    for (int i = 0; i < files.length; i++) { 
                        try{ 
                            downloadFile(files[i], localBaseDir, remoteBaseDir); 
                        }catch(Exception e){ 
                            logger.error(e); 
                            logger.error("<"+files[i].getName()+">下载失败"); 
                        } 
                    } 
                } 
            } catch (Exception e) { 
                logger.error(e); 
                logger.error("下载过程中出现异常"); 
            } 
        }else{
            logger.error("链接失败！");
        }
        
    }
    
    
    /** 
     * 
     * 下载FTP文件 
     * 当你需要下载FTP文件的时候，调用此方法 
     * 根据<b>获取的文件名，本地地址，远程地址</b>进行下载 
     * 
     * @param ftpFile 
     * @param relativeLocalPath 
     * @param relativeRemotePath 
     */ 
    private void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) { 
        if (ftpFile.isFile()) {
            if (ftpFile.getName().indexOf("?") == -1) { 
                OutputStream outputStream = null; 
                try { 
                    File locaFile= new File(relativeLocalPath+ ftpFile.getName()); 
                    //判断文件是否存在，存在则返回 
                    if(locaFile.exists()){ 
                        return; 
                    }else{ 
                        outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); 
                        ftp.retrieveFile(ftpFile.getName(), outputStream); 
                        outputStream.flush(); 
                        outputStream.close(); 
                    } 
                } catch (Exception e) { 
                    logger.error(e);
                } finally { 
                    try { 
                        if (outputStream != null){ 
                            outputStream.close(); 
                        }
                    } catch (IOException e) { 
                       logger.error("输出文件流异常"); 
                    } 
                } 
            } 
        } else { 
            String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); 
            String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); 
            File fl = new File(newlocalRelatePath); 
            if (!fl.exists()) { 
                fl.mkdirs(); 
            } 
            try { 
                newlocalRelatePath = newlocalRelatePath + '/'; 
                newRemote = newRemote + "/"; 
                String currentWorkDir = ftpFile.getName().toString(); 
                boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); 
                if (changedir) { 
                    FTPFile[] files = null; 
                    files = ftp.listFiles(); 
                    for (int i = 0; i < files.length; i++) { 
                        downloadFile(files[i], newlocalRelatePath, newRemote); 
                    } 
                } 
                if (changedir){
                    ftp.changeToParentDirectory(); 
                } 
            } catch (Exception e) { 
                logger.error(e);
            } 
        } 
    } 
    
    public void initFtp(int i ) {
    	FtpTo f=new FtpTo();
    	switch (i) {
			case 1:
		        f.setIpAddr("qxu1649330360.my3w.com");
		        f.setUserName("qxu1649330360");
		        f.setPwd("123456gxg");
				break;
			case 2:
		        f.setIpAddr("vhost363.cloudvhost.cn");
		        f.setUserName("webmaster@HA208125");
		        f.setPwd("t8Ako1Is8uxJiLyy");
				break;
			case 3:
		        f.setIpAddr("hz198758.ftp.aliapp.com");
		        f.setUserName("hz198758");
		        f.setPwd("123456Gxg");
				break;
    	}
        try {
			connectFtp(f);
		} catch (Exception e) {
			System.out.println("链接到FTP异常！");
			e.printStackTrace();
		}
    }
    
    /**
     * 上传文件到指定FTP服务器上
     * @param path	待上传文件目录路径
     * @param i	FTP服务器：1、kc890；2、kaichejiqiao；3、1nsh
     */
    public void uploadHtmls(String path, int i) {
    	initFtp(i);
        File file = new File(path);
        try {
        	String dir = "/htdocs/";
        	switch (i) {
				case 2:
			        dir =  "/WEB/";
					break;
	    	}
        	//把文件上传在ftp上
			upload(file, dir, false);
			ftp.logout();
		} catch (Exception e) {
			logger.error("上传文件或ftp退出错误， {}",  e);
		}
    }
    public static void main(String[] args) throws Exception{  
//    	uploadHtmls("F:/资料/项目/驾车技巧/html/kaichejiqiao/20160307/", 1);
            System.out.println("ok");
       }  
    
}
